package org.example.utils;

import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.AppsV1Api;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.*;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Description: 封装k8s基本操作
 *
 * @author shenguangyang
 */
public class KubernetesUtils {
    /**
     * 在使用前要先调用该方法,设置k8s集群的配置
     * @param kubeConfig resources 路径下的文件 比如你直接放在 resources 路径下直接输入 k8s-config
     *                   如果你放在 resources/config 路径下 ，就应该输入 config/k8s-config
     * @throws ApiException
     * @throws IOException
     */
    public static void init(String kubeConfig) throws ApiException, IOException {
        File kubeConfigFile = ResourceUtils.getFile("classpath:" + kubeConfig);
        //加载k8s, config
        ApiClient client = ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigFile))).build();
        //将加载config的client设置为默认的client
        Configuration.setDefaultApiClient(client);
//        ApiKeyAuth BearerToken = (ApiKeyAuth) defaultClient.getAuthentication("BearerToken");
//        BearerToken.setApiKey("YOUR API KEY");

    }

    /**
     * 封装pod的操作
     */
    public static class Pod {

        /**
         * 打印所有的pod
         * @return pod集合
         * @throws ApiException
         */
        public static V1PodList getAll() throws ApiException {
            return new CoreV1Api().listPodForAllNamespaces(null,null,null,null,null,null,null,
                    null,null);
        }

        /**
         * 创建pod
         *
         * @param nameSpace ：名称空间
         * @param body      ：pod
         * @return
         * @throws ApiException
         */
        public static V1Pod create(String nameSpace, V1Pod body) throws ApiException {
            return new CoreV1Api().createNamespacedPod(nameSpace, body, "true ", "true", null);
        }

        /**
         * 删除pod
         *
         * @param nameSpace
         * @param podName
         * @throws Exception
         */
        public static void delete(String nameSpace, String podName) throws Exception {
            new CoreV1Api().deleteNamespacedPod(podName, nameSpace, "true", null, null, null, null, null);
        }
    }

    /**
     * 封装 Service 操作
     */
    public static class Service {
        /**
         * 创建service
         *
         * @param nameSpace
         * @param sv
         * @throws ApiException
         */
        public static void create(String nameSpace, V1Service sv) throws ApiException {
            new CoreV1Api().createNamespacedService(nameSpace, sv, "true", "true", null);
        }

        /**
         * 删除service
         *
         * @param nameSpace
         * @param serviceName
         * @throws Exception
         */
        public static void delete(String nameSpace, String serviceName) throws Exception {
            new CoreV1Api().deleteNamespacedService(serviceName, nameSpace, null, null, null, null, null, null);
        }

    }

    /**
     * 封装 Deployment 操作
     */
    public static class Deployment {
        /**
         * 创建deployment
         *
         * @param nameSpace
         * @param body
         * @throws ApiException
         */
        public static void create(String nameSpace, V1Deployment body) throws ApiException {
            new AppsV1Api().createNamespacedDeployment(nameSpace, body, "true", "true", null);
        }

        /**
         * 刪除namespace
         *
         * @param nameSpace
         * @param deployeName
         * @throws ApiException
         */
        public static void delete(String nameSpace, String deployeName) throws ApiException {
            new AppsV1Api().deleteNamespacedDeployment(deployeName, nameSpace, "true", null, null, null, null, null);
        }
    }

    public static void main(String[] args) throws IOException, ApiException {
        KubernetesUtils.init("config/k8s-config");
        V1PodList allPod = Pod.getAll();
        System.out.println(allPod.getApiVersion());

        // 创建pod
        V1Pod v1Pod = new V1Pod();
        v1Pod.setKind("Pod");
        v1Pod.setApiVersion("v1");

        V1ObjectMeta v1ObjectMeta = new V1ObjectMeta();
        v1ObjectMeta.setName("pod-tomcat-test");
        v1ObjectMeta.setNamespace("default");
        v1Pod.setMetadata(v1ObjectMeta);

        V1PodSpec v1PodSpec = new V1PodSpec();
        List<V1Container> containerList = new ArrayList<>();
        V1Container v1Container = new V1Container();
        v1Container.setImage("tomcat");
        v1Container.setName("tomcat-container");
        containerList.add(v1Container);
        List<String> list = Arrays.asList("sh","-c","echo tomcat-container is running! && sleep 10");
        v1Container.setCommand(list);
        v1PodSpec.setContainers(containerList);

        v1Pod.setSpec(v1PodSpec);
        Pod.create("default",v1Pod);
    }
}
